const cloud = require("wx-server-sdk");

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });

const db = cloud.database();
const _ = db.command;

const normalizeString = value =>
  typeof value === "string" ? value.trim() : "";

const cancelRegistration = async event => {
  const wxContext = cloud.getWXContext();
  const openID = wxContext.OPENID;

  if (!openID) {
    return { success: false, error: "未获取到用户信息" };
  }

  const activityID = normalizeString(event && event.activityID);
  if (!activityID) {
    return { success: false, error: "缺少活动编号" };
  }

  const groupsRes = await db.collection("Activity_Group_Information")
    .where({ ActivityID: activityID })
    .get();
  const groupIDs = (groupsRes.data || []).map(item => item._id);

  const fieldsRes = await db.collection("Activity_Registration_Information_Fields")
    .where({ ActivityID: activityID })
    .get();
  const fieldIDs = (fieldsRes.data || []).map(item => item._id);

  if (groupIDs.length === 0 && fieldIDs.length === 0) {
    return { success: true };
  }

  try {
    const result = await db.runTransaction(async transaction => {
      if (groupIDs.length > 0) {
        await transaction.collection("Group_Registration_Information")
          .where({
            GroupID: _.in(groupIDs),
            OpenID: openID
          })
          .remove();
      }

      if (fieldIDs.length > 0) {
        await transaction.collection("Group_Registration_Custom_Fields")
          .where({
            FieldID: _.in(fieldIDs),
            OpenID: openID
          })
          .remove();
      }

      return { success: true };
    });

    return result;
  } catch (error) {
    return {
      success: false,
      error: error.message || "数据库操作失败"
    };
  }
};

exports.main = async (event, context) => {
  return cancelRegistration(event, context);
};
